import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AppHttpResponse } from '../interface';
import { StorageService } from './storage.service';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  constructor(
    private router: Router,
    private http: HttpClient,
    private storage: StorageService
  ) {}

  /**
   * 登录
   * @param data 账号数据
   */
  login(data: any): Observable<AppHttpResponse<any>> {
    // 登陆前清除所有缓存数据
    this.storage.clear();
    const params = new HttpParams({ fromObject: data });
    return this.http
      .post<AppHttpResponse<string>>('/api/auth/login', params)
      .pipe(
        tap((res) => {
          if (res.success) {
            this.storage.set('access_token', res.data);
          }
        })
      );
  }

  /**
   * 退出登录，并跳转至登录
   */
  logout(): void {
    this.storage.clear();
    this.router.navigateByUrl('/auth/login');
  }
}
